﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Net.TheBoredCoders.SoundBoard.Controls;

namespace Net.TheBoredCoders.SoundBoard
{
    /// <summary>
    /// Main Form for the Application - loads content dynamically
    /// </summary>
    public partial class DynamicForm : Form
    {
        #region internal Fields

        /// <summary>internal reminder for the Samples Root-Directory</summary>
        private string rootDirSoundFiles;

        #endregion

        #region Constructor, Load-, and Close-Events

        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicForm"/> class.
        /// </summary>
        public DynamicForm()
        {
            InitializeComponent();
            // apply the Path for the Sound-Root
            setSamplesRootDirectory();
        }

        /// <summary>
        /// Handles the Load event of the DynamicForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DynamicForm_Load(object sender, EventArgs e)
        {
            // ToDo: create if missing ? (later, if installer is ready and working)
            if (!System.IO.Directory.Exists(rootDirSoundFiles))
            {
                MessageBox.Show("The Sample directory {0} does not exists!", "Missing directory", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }


            // load data and show in ui
            reLoadData(rootDirSoundFiles);
            

            // // // Old Code for loading the data
            ////Root Page
            //TabPage root = HelperClass.CreateSoundBoardTabPage(Properties.Settings.Default.Label_RootDir, rootDirSoundFiles);
            //tabControlDynamic.TabPages.Add(root);
            ////Sub directories
            //String[] subDirs = System.IO.Directory.GetDirectories(rootDirSoundFiles);
            //foreach (String subDirecotry in subDirs)
            //{
            //    //Create new tab page
            //    tabControlDynamic.TabPages.Add(HelperClass.CreateSoundBoardTabPage(HelperClass.InsertSpaces(subDirecotry.Remove(0, rootDirSoundFiles.Length)), subDirecotry));
            //}
        }

        /// <summary>
        /// Handles the FormClosing event of the DynamicForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        private void DynamicForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (Properties.Settings.Default.App_ConfirmClose)
                {
                    if (DialogResult.Yes != MessageBox.Show(this, "Do you really want to exit?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        #endregion

        #region Menu Events

        /// <summary>
        /// Handles the Click event of the mniAbout control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mniAbout_Click(object sender, EventArgs e)
        {
            AboutForm tmpDialog = new AboutForm();
            tmpDialog.ShowDialog();
        }

        /// <summary>
        /// Handles the Click event of the mniExitTool control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mniExitTool_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the mniAppSettings control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mniAppSettings_Click(object sender, EventArgs e)
        {
            SettingsForm tmpDialog = new SettingsForm();
            tmpDialog.ShowDialog();
        }

        /// <summary>
        /// Handles the Click event of the mniReloadContent control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mniReloadContent_Click(object sender, EventArgs e)
        {
            // reload data and show in ui
            reLoadData(rootDirSoundFiles);
        }

        #endregion

        #region internal worker

        /// <summary>
        /// Reloads data and ui.
        /// </summary>
        /// <param name="rootDir">The root dir.</param>
        private void reLoadData(string rootDir)
        {
            // read data
            SampleData sampleData = HelperClass.ReadContentDirectory(rootDir);
            // (re-)generate ui
            tabControlDynamic.TabPages.Clear(); // remove possible old pages (complete re-create)
            // create tabs recusive from root-object
            uiLoader(sampleData);
        }

        /// <summary>
        /// Generate the Tab-Pages from Sample-Data - working recursive.
        /// </summary>
        /// <param name="directoryItem">The directory item to process.</param>
        private void uiLoader(SampleData directoryItem)
        {
            // get samples in directory
            List<SampleData> tmpList = directoryItem.GetChildItems(DataType.Sample);
            if (tmpList.Count > 0) // there is at least one sample in the directory
            {
                // create tab-page, fill with buttons and add to tab-control
                tabControlDynamic.TabPages.Add(HelperClass.CreateSoundBoardTabPage(directoryItem));
            }
            // check for sub-dirs
            tmpList = directoryItem.GetChildItems(DataType.Directory);
            foreach (SampleData item in tmpList)
            {
                // call the method recursive for all sub-folders
                uiLoader(item);
            }
        }

        /// <summary>
        /// Sets the root directory for the Samples.
        /// </summary>
        private void setSamplesRootDirectory()
        {
            // set the default-path
            string defaultDirectory = rootDirSoundFiles = System.IO.Path.Combine(Application.StartupPath, "Sounds");
            // using StartupPath and Path.Combine to use the Application on Mono without Path-Trouble
            bool useDefault = true;

            // check for a custom path in settings
            if (Properties.Settings.Default.Path_Content.Trim() != string.Empty)
            {
                // we have a custom path - check it
                if (System.IO.Directory.Exists(Properties.Settings.Default.Path_Content))
                {
                    rootDirSoundFiles = Properties.Settings.Default.Path_Content;
                    useDefault = false;
                }
            }
            // ToDo: check for content-dir in userspace (will be created by installer later)
            if (useDefault) // no (valid) custom sounds-directory found yet - use default
            {
                rootDirSoundFiles = defaultDirectory;
            }
            // define custom path if not already done (first start)
            if (Properties.Settings.Default.Path_Content.Trim() == string.Empty)
            {
                // no path set yet - apply default to settings and save
                Properties.Settings.Default.Path_Content = rootDirSoundFiles;
                Properties.Settings.Default.Save();
            }
        }

        #endregion
    }
}